import { Store } from "../../core";

import OpenButton from "./OpenButton";
import StoreProps from "./StoreProps";
import { ChangeEvent, FC, ReactElement } from "react";

export interface RenderOpenProps {
  onClick: (e: ChangeEvent<HTMLInputElement>) => void;
}

type RenderOpen = (props: RenderOpenProps) => ReactElement;

export interface OpenProps {
  children?: RenderOpen;
}

const Open: FC<{
  children?: RenderOpen;
  store: Store<StoreProps>;
}> = ({ store, children }) => {
  const handleOpenFiles = (e: ChangeEvent<HTMLInputElement>): void => {
    const files = e.target.files;
    if (!files || !files.length) {
      return;
    }
    const openFile = store.get("openFile");
    if (openFile) {
      openFile(files[0]);
    }
  };

  const defaultChildren = (props: RenderOpenProps) => (
    <OpenButton onClick={props.onClick} />
  );
  const render = children || defaultChildren;

  return render({
    onClick: handleOpenFiles,
  });
};

export default Open;
